package com.room.search.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.room.search.constant.Constants;
import com.room.search.constant.HttpStatus;
import com.room.search.core.redis.RedisCache;
import com.room.search.response.RoomResult;
import com.room.search.security.jwt.TokenProvider;
import com.room.search.util.ServletUtils;
import com.room.search.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义退出处理类 返回成功
 *
 * @author bright
 */
@Configuration
public class LogoutSuccessHandlerImpl implements LogoutSuccessHandler
{
    private final Logger log = LoggerFactory.getLogger(this.getClass());
    private static final String HEADER = "Authorization";

    @Autowired
    private ObjectMapper mapper;
    @Autowired
    private RedisCache redisCache;
    private final TokenProvider tokenProvider;

    public LogoutSuccessHandlerImpl(TokenProvider tokenProvider) {
        this.tokenProvider = tokenProvider;
    }

    /**
     * 退出处理
     */
    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
            throws IOException
    {
        String token = getToken(request);

        if (!StringUtils.isNotEmpty(token) && !tokenProvider.validateToken(token)) {
            log.info("准备用户退出系统");
        }
        String username = tokenProvider.getAuthentication(token).getName();
        String key = Constants.LOGIN_USER_KEY + username;
        redisCache.deleteObject(key);

        ServletUtils.renderString(response, mapper.writeValueAsString(RoomResult.error(HttpStatus.SUCCESS, "退出成功")));
    }


    /**
     * 获取请求token
     *
     * @return token
     */
    private String getToken(HttpServletRequest request)
    {
        String token = request.getHeader(HEADER);
        if (StringUtils.isNotEmpty(token) && token.startsWith(Constants.TOKEN_PREFIX))
        {
            token = token.replace(Constants.TOKEN_PREFIX, "");
        }
        return token;
    }
}
